package cn.edu.xmist.java.util.hashmap;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhongjinbin 2021/4/9
 * @since 0.0.1
 * 初始容量测试demo
 */
public class HashMapCapacityDemo {

    /**
     * 容量测试
     * @param initCapacity 入参容量
     * @return 实际容量
     * @throws Exception
     */
    public static int capacityTest(int initCapacity) throws Exception {

        Map<String, String> map = new HashMap<String, String>(initCapacity);

        // 通过反射获取容量变量capacity,并调用map对象
        Method capacity = map.getClass().getDeclaredMethod("capacity");
        capacity.setAccessible(true);
        Integer realCapacity = (Integer) capacity.invoke(map);
        System.out.println("入参容量为" + initCapacity + "时，实际容量为" + realCapacity);
        return realCapacity.intValue();
    }

    public static void main(String[] args) {
        try {
            capacityTest(1);
            capacityTest(2);
            capacityTest(3);
            capacityTest(4);
            capacityTest(7);
            capacityTest(21);
            capacityTest(1500000000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
